package com.rockcent.mall.lib.helper;

import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;
import com.rockcent.common.common.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 企业短信通
 * Created by zhangjh on 2017/5/9.
 */
public class SmsConSmsStrategy implements SMSStrategy {
    private static Logger log = LoggerFactory.getLogger(SmsConSmsStrategy.class);

    @Autowired
    private AsyncHttpClient asyncHttpClient;

    public static final String HOSTNAME = "http://115.236.100.12:8811/sms.aspx";
    public static final String USER_ID = "219";
    public static final String ACCOUNT = "1069032505";
    public static final String PASS_WORD = "lechen123";
    public static final String EXTNO = "";
    public static final String CONTENT_PREFIX = "【络享】";

    private DocumentBuilder builder;

    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            log.error(e.getMessage(), e);
        }
    }


    @Override
    public String send(String mobile, String code, String name) throws BusinessException {
        return send(mobile, code);
    }

    @Override
    public String send(String mobile, String content) throws BusinessException {
        String response;
        try {
            AsyncHttpClient.BoundRequestBuilder request = asyncHttpClient.preparePost(HOSTNAME);
            request.addParameter("action", "send");
            request.addParameter("userid", USER_ID);
            request.addParameter("account", ACCOUNT);
            request.addParameter("password", PASS_WORD);
            request.addParameter("sendTime", "");
            request.addParameter("extno", "");
            request.addParameter("mobile", mobile);
            request.addParameter("content", CONTENT_PREFIX + content);
//            log.info("请求地址： {}", HOSTNAME);
            Future<Response> f = request.execute();
            response = f.get().getResponseBody();
            //log.info("返回内容：{}", response);
        } catch (IOException | InterruptedException | ExecutionException e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("发送验证码失败");
        }

        return response;
    }

    @Override
    public boolean handleResponse(String response) {
        if (response == null || response.isEmpty())
            return false;

        String returnstatus = null;
        String message = null;
        String remainpoint = null;
        String taskID = null;
        String successCounts = null;

        try {
            Document doc = builder.parse(new InputSource(new StringReader(response)));
            Element root = doc.getDocumentElement();
            NodeList nodeList = root.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() != Node.ELEMENT_NODE)
                    continue;

                switch (node.getNodeName()) {
                    case "returnstatus":
                        returnstatus = node.getTextContent();
                        break;
                    case "message":
                        message = node.getTextContent();
                        break;
                    case "remainpoint":
                        remainpoint = node.getTextContent();
                        break;
                    case "taskID":
                        taskID = node.getTextContent();
                        break;
                    case "successCounts":
                        successCounts = node.getTextContent();
                        break;
                    default:
                        break;
                }
            }

        } catch (SAXException | IOException e) {
            log.error(e.getMessage(), e);
        }

        log.info("状态：{}，信息：{}，余额：{}，序列ID：{}，成功短信数：{}",
                returnstatus, message, remainpoint, taskID, successCounts);
        return "Success".equals(returnstatus);
    }
}
